package com.pin.zheng.xingmulibrary.util;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ServerManager {
    private ServerSocket mServerSocket;
    private Socket mSocket;
    private StringBuffer stringBuffer = new StringBuffer();
    private Handler handler = new Handler(Looper.getMainLooper());
    Context context;
    private ServerManager() {
    }

    private static ServerManager instance;

    public static synchronized ServerManager getInstance() {
        if (instance == null) {
            synchronized (TcpManager.class) {
                instance = new ServerManager();
            }
        }
        return instance;
    }

    public ServerManager initSocket(Context context) {
        this.context=context;
        init();
        return this;
    }

    private void init() {
        try {
            mServerSocket = new ServerSocket(6000);//端口号5000
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mServerSocket == null) {
            try {
                mServerSocket = new ServerSocket();
                mServerSocket.setReuseAddress(true);
                mServerSocket.bind(new InetSocketAddress(6000));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //启动服务线程
        SocketAcceptThread socketAcceptThread = new SocketAcceptThread();
        socketAcceptThread.start();
    }


    /**
     * 连接线程
     * 得到Socket
     */
    class SocketAcceptThread extends Thread {
        @Override
        public void run() {
            try {
                //等待客户端的连接，Accept会阻塞，直到建立连接，
                //所以需要放在子线程中运行
                mSocket = mServerSocket.accept();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            //启动消息接收线程
            startReader(mSocket);
        }
    }

    /**
     * 从参数的Socket里获取最新的消息
     */
//    private void startReader(final Socket socket) {
//
//        new Thread() {
//            @Override
//            public void run() {
//                DataInputStream reader;
//                try {
//                    // 获取读取流
//                    reader = new DataInputStream(socket.getInputStream());
//                    LogUtils.e("客户端的信息");
//                    while (true) {
//                        // 读取数据
//                        final String msg = reader.readUTF();
//                        Log.d("TAG", "客户端的信息:" + msg);
//
//                        //告知客户端消息收到
//                        DataOutputStream writer = new DataOutputStream(mSocket.getOutputStream());
//                        writer.writeUTF("收到:" + msg); // 写一个UTF-8的信息
//                        //发消息更新UI
//                        handler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (onReceiveDataListener != null) {
//                                    onReceiveDataListener.onReceiveData(msg);
//                                }
//                            }
//                        });
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    close();
//                    init();
//                }
//            }
//        }.start();
//    }

    /**
     * 从参数的Socket里获取最新的消息
     */
    private void startReader(final Socket socket) {

        new Thread() {
            @Override
            public void run() {
                DataInputStream reader;
                try {
                    // 获取读取流
                    reader = new DataInputStream(socket.getInputStream());
                    LogUtils.e("客户端的信息");
                    while (true) {
                        // 读取数据
                        String msg = reader.readUTF();
                        Log.d("TAG", "客户端的信息:" + msg);
                        if (msg.contains(".apk")) {
                            //接收到的文件要存储的位置
                            File directory = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/");
                            if (!directory.exists()) {
                                directory.mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(directory.getAbsolutePath() + "/" + msg);
                            // 开始接收文件
                            byte[] bytes = new byte[1024];
                            int length = 0;
                            while ((length = reader.read(bytes, 0, bytes.length)) != -1) {
                                fos.write(bytes, 0, length);
                                fos.flush();
                            }
                            reader.close();
                            fos.close();
                            socket.close();
                            Intent intent = new Intent("action_android_pad_wifi_updata");
                            intent.putExtra("path", context.getExternalFilesDir(null).getAbsolutePath() + "/" + msg);
                            context.sendBroadcast(intent);
                        } else {
                            //告知客户端消息收到
                            //发消息更新UI
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (onReceiveDataListener != null) {
                                        LogUtils.e(msg);
                                        onReceiveDataListener.onReceiveData(msg);
                                    }
                                }
                            });
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    close();
                    init();
                }
            }
        }.start();
    }

    /*发送数据*/
    public void sendData(final String data) {
        if (mSocket != null && mSocket.isConnected()) {
            /*发送指令*/
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        DataOutputStream writer = new DataOutputStream(mSocket.getOutputStream());
                        writer.writeUTF(data); // 写一个UTF-8的信息
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }).start();

        } else {
            LogUtils.d("socket连接错误,请重试");
        }
    }

    private void close() {
        if (mServerSocket != null) {
            try {
                mServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mSocket != null) {
            try {
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface OnReceiveDataListener {
        void onReceiveData(String str);
    }

    public OnReceiveDataListener onReceiveDataListener;

    public void setOnReceiveDataListener(OnReceiveDataListener onReceiveDataListener) {
        this.onReceiveDataListener = onReceiveDataListener;
    }

}
